import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../common/api/index.dart';
import '../../common/models/index.dart';
import '../../common/services/index.dart';
import '../../common/utils/index.dart';
import '../../common/values/index.dart';
import 'state.dart';

class HomeController extends GetxController with WidgetsBindingObserver {
  HomeController();
  final eventId = 'home';
  final state = HomeState();
  final eventBus = EventBus();
  //建议模式
  var simpleMode = false;
  var pageController = PageController();

  // 门户 id 缓存
  final Map<AppIndexModule, String> portalCache  = {};


  /// 个人语言环境
  void _personLanguage() {
    O2Person? userJson = O2ApiManager.instance.loadUserFromSP();
    if (userJson != null) {
      final lan = LanguageListExt.getFromPcKey(userJson.language ?? '');
      final currentLan = LanguageListExt.getCurrentLanguage();
      if (lan != currentLan) {
        // update language
        Get.updateLocale(lan.getLocale());
        SharedPreferenceService.to.putString(SharedPreferenceService.languageSaveKey, lan.getKey());
      }
    }
  }
  /// eventBus 
  void _bindEventBusListener() {
    // 未读消息数量监听
    eventBus.on(EventBus.imUnReadNumberMsg, eventId, (f) {
      OLogger.d('接收到未读消息： $f');
      if (f is int) {
        state.unReadNumber = f;
      }
    });
    //监听websocket消息
    eventBus.on(EventBus.websocketCreateImMsg, eventId, (arg) {
      OLogger.d("收到websocket im 新消息！刷新Home");
      if (arg is IMMessage) {
        loadConversationList();
      }
    });
  }

  /// 加载数据 初始化界面
  void _initLoadData() async {
    simpleMode = ProgramCenterService.to.isSimpleMode();
    state.homeTabList.clear();
    // 桌面版本 目前只开放消息和设置
    if (GetPlatform.isDesktop) {
      state.homeTabList.addAll([AppIndexModule.im, AppIndexModule.settings]);
    } else {
      final pages = ProgramCenterService.to.appIndexPages();
      if (pages.isEmpty) {
        // 老配置，没有页面列表
        if (simpleMode) {
          state.homeTabList
              .addAll([AppIndexModule.home, AppIndexModule.settings]);
        } else {
          state.homeTabList.addAll([
            AppIndexModule.im,
            AppIndexModule.contact,
            AppIndexModule.home,
            AppIndexModule.app,
            AppIndexModule.settings
          ]);
        }
      } else {
        List<AppIndexModule> tabs = [];
        if (ProgramCenterService.to.isIndexCentered()) {
          tabs = [
            AppIndexModule.im,
            AppIndexModule.contact,
            AppIndexModule.home,
            AppIndexModule.app,
            AppIndexModule.settings
          ];
        } else {
          for (var e in pages) {
              if (e == AppIndexModule.im.key()) {
                tabs.add(AppIndexModule.im);
              }
              if (e == AppIndexModule.contact.key()) {
                tabs.add(AppIndexModule.contact);
              }
              if (e == AppIndexModule.home.key()) {
                tabs.add(AppIndexModule.home);
              }
              if (e == AppIndexModule.app.key()) {
                tabs.add(AppIndexModule.app);
              }
              if (e == AppIndexModule.settings.key()) {
                tabs.add(AppIndexModule.settings);
              }
            }
            if (tabs.isEmpty) {
              tabs = [
                AppIndexModule.im,
                AppIndexModule.contact,
                AppIndexModule.home,
                AppIndexModule.app,
                AppIndexModule.settings
              ];
            }
             // 必须有首页
            if (!tabs.contains(AppIndexModule.home)) {
              tabs.add(AppIndexModule.home);
            }
            // 必须有设置页面
            if (!tabs.contains(AppIndexModule.settings)) {
              tabs.add(AppIndexModule.settings);
            }
            tabs.sort(((a, b) => a.orderNumber().compareTo(b.orderNumber())));
        }
        state.homeTabList.addAll(tabs);
      }
    }
    state.currentIndex =  state.homeTabList.indexWhere((element) => element == AppIndexModule.home); // 首页的序号
    pageController = PageController(initialPage: state.currentIndex);
    state.showBottomBar = true;
  }

  /// 点击底部菜单
  void handleNavBarClick(int index) {
    if (state.currentIndex == index) { // 重复点击 如果是门户 发送刷新事件消息
      final portalId = portalCache[state.homeTabList[index]] ;
      if (portalId != null && portalId.isNotEmpty) {
         eventBus.emit(EventBus.refreshPortalMsg, portalId);
      }
      return;
    }
    state.currentIndex = index;
    pageController.jumpToPage(index);
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    WidgetsBinding.instance.addObserver(this);
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    // 个人语言切换
    // _personLanguage();
    // 绑定
    _bindEventBusListener();
    // 初始化界面数据
    _initLoadData();
    // websocket
    O2WebsocketClient().open();
    // 极速打卡
    FastCheckInService.instance.start();
    // 自动检查更新 app
    final isOpenUpdate = SharedPreferenceService.to.getBool(SharedPreferenceService.appUpdateUserSwitchKey, defaultValue: true);
    if (isOpenUpdate) { // 用户开关
      O2AndroidAppUpdateManager().checkUpdate();
    }
    // 移动端需要绑定设备
    if (GetPlatform.isMobile) {
      bindDeviceForJPush();
      // 清除角标
      O2ApiManager.instance.jpushClearNotifyBadge();
      // 检查通知权限
      O2ApiManager.instance.jpushCheckIsNotificationEnabled();
    }
    _initContactPermission();
    _initPanV3();
    _checkAttendanceVersion();
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    eventBus.off(EventBus.imUnReadNumberMsg, eventId);
    eventBus.off(EventBus.websocketCreateImMsg, eventId);
    WidgetsBinding.instance.removeObserver(this);
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) async {
    OLogger.d("LifecycleState ==========  $state");
    if (state == AppLifecycleState.resumed) {
      OLogger.d('进入应用，重新连接websocket！！！！');
      O2WebsocketClient().open();
      FastCheckInService.instance.start();
      // 清除角标
      O2ApiManager.instance.jpushClearNotifyBadge();
    }
  }

  /// 获取会话列表 读取未读消息数量
  Future<void> loadConversationList() async {
    var list = await MessageCommunicationService.to.myConversationList();
    if (list != null && list.isNotEmpty) {
      int unReadNumber = 0;
      for (var element in list) {
        unReadNumber += element.unreadNumber ?? 0;
      }
      state.unReadNumber = unReadNumber;
    }
  }
  /// 绑定设备号，极光推送使用
  Future<void> bindDeviceForJPush() async {
    var deviceId = O2ApiManager.instance.deviceID;
    if (deviceId.isNotEmpty) {
      OLogger.i('当前极光推送 id：$deviceId');
      var result = await JpushAssembleControlService.to.bindDevice(deviceId);
      if (result == null) {
        OLogger.e('设备号绑定失败！！！');
      }
    } else {
      OLogger.e('没有获取到极光推送的设备号！！！！！');
    }
  }

  Future<void> _initContactPermission() async {
    OLogger.d('查询通讯录权限');
    if (OrganizationPermissionService.to.baseUrl().isNotEmpty) {
      var view = ProgramCenterService.to.appStyle?.contactPermissionView ??
          O2.addressPowerView;
      if (view.isNotEmpty) {
        var data =
            await OrganizationPermissionService.to.getPermissionViewInfo(view);
        if (data != null) {
          O2ContactPermissionManager.instance.initData(data);
        }
      }
    } else {
      OLogger.d('没有安装通讯录应用！');
    }
  }

  ///
  /// v3 网盘 需要安装应用
  /// 检查是否已经安装
  Future<void> _initPanV3() async {
    OLogger.d('查询V3网盘是否已经安装');
    if (FileAssembleService.to.v3BaseUrl().isNotEmpty) {
      var echo = await FileAssembleService.to.v3ZoneList();
      if (echo != null) {
        OLogger.d('V3网盘 已安装。。。。。。。。。');
        SharedPreferenceService.to
            .putBool(SharedPreferenceService.v3PanAppIsInstallKey, true);
      } else {
        SharedPreferenceService.to
            .putBool(SharedPreferenceService.v3PanAppIsInstallKey, false);
      }
    } else {
      OLogger.e('没有v3网盘应用！');
      SharedPreferenceService.to
          .putBool(SharedPreferenceService.v3PanAppIsInstallKey, false);
    }
  }

  Future<void> _checkAttendanceVersion() async {
    final result = await AttendanceAssembleControlService.to.config();
    if (result != null && result.closeOldAttendance == true) {
      SharedPreferenceService.to
          .putBool(SharedPreferenceService.v2AttendanceKey, true);
    } else {
      SharedPreferenceService.to
          .putBool(SharedPreferenceService.v2AttendanceKey, false);
    }
  }

  DateTime? lastPopTime;

  /// 退出
  Future<bool> onWillPop() async {
    OLogger.d('onWillPop=====================');
    if (!Platform.isAndroid) {
      // 关闭极速打卡
      FastCheckInService.instance.stop();
      return true;
    }
    if (lastPopTime == null ||
        DateTime.now().difference(lastPopTime!) > const Duration(seconds: 2)) {
      lastPopTime = DateTime.now();
      Loading.toast('common_double_click_quit'.tr);
      return false;
    } else {
      lastPopTime = DateTime.now();
      // 关闭极速打卡
      FastCheckInService.instance.stop();
      return true;
    }
  }

  ///
  /// 存储权限
  ///
  // Future<bool> _storagePermission() async {
  //   var status = await Permission.manageExternalStorage.status;
  //   if (status == PermissionStatus.granted) {
  //     return true;
  //   } else {
  //     status = await Permission.manageExternalStorage.request();
  //     if (status == PermissionStatus.granted) {
  //       return true;
  //     }
  //   }
  //   return false;
  // }
}
